import { Inject, Config, Controller, Post, Body } from '@midwayjs/core';
import { AdminService } from '../service/admin.service';
import { Context } from '@midwayjs/koa';
import { UserContext } from '../common/UserContext';
import { Constant } from '../common/Constant';
import { RedisService } from '@midwayjs/redis';
import { JwtService } from '@midwayjs/jwt';
import { ILogger } from '@midwayjs/core';
import { Validate } from '@midwayjs/validate';

@Controller('/api/admin')
export class APIController {

    @Inject()
    logger: ILogger;

    @Inject()
    ctx: Context;

    @Inject()
    adminService: AdminService;

    @Inject()
    cacheUtil: RedisService;

    @Inject()
    jwtUtil: JwtService;

    @Config('jwt')
    jwtConfig;

    @Validate()
    @Post('/login', { description: '登录' })
    async login(@Body() body: {storenum: number, password: string}) {
        console.log("body:",body);
        const { storenum, password } = body;
        const store = await this.adminService.login(storenum,password)
        const uc: UserContext = new UserContext(store.storenum,store.name,store.phone);
        const at = await this.jwtUtil.sign({ ...uc });
        const key = Constant.TOKEM + ':' + store.storenum + ':' + at;
        const expiresIn = this.jwtConfig.expiresIn;//有效时间
        this.cacheUtil.set(key, JSON.stringify(uc), 'EX', expiresIn);
        return { success: true, message: '获取token成功', data: { token: 'Bearer '+at,accessToken:at, expiresIn: expiresIn } }
    }
}